/*
        Script to show single item picker, show predefined values editor etc
*/


function ISM_SimpleItemPicker(txtElId, options) {
    var $this = jQuery(this);
    var result= {
        'obj':$this,
        txtElId : txtElId,
        txtEl: jQuery("#" + txtElId),
        
        options:jQuery.extend(true, {}, this.options, { dtypes: ['integer', 'ntext', 'nvarchar', '--date--'], labels: [] }, options)
    };
    result.node = jQuery.extend(true, result.options.node, result.options.defaultnode);
    
    result.options.node.data = result.txtEl.val();

    result.RefreshTextBox= function (node,obj) {
        var obj = this;
            var resnode = node ? node : obj.options.node;
            this.txtEl.val(resnode.data); //get data from current node
        };
    result.TransformTemplate= function (template, element) {
        var obj = this;
            var res = String(template);
            for (var pname in element) {
                res = res.replace(new RegExp("##" + pname + "##", "g"), element[pname]);
            }
            res = res.replace(new RegExp("##[^##]*##", "g"), ""); //replace rest to empty string
            return { 'result': res, 'template': template, 'data': element };
        };
        result.showNodeInfo = function (cType, node, container, obj) {
            var obj = this;
            var resHtml = obj.TransformTemplate(node.template, node);
            if (node.element) node.element.remove();
            node.element = jQuery(resHtml.result);
            node.element.appendTo(container);
            container.nodes.push(node); //save list of nodes(one)        
            //buttons
            var bsContainer = node.element.find("." + node.buttonscss);
            bsContainer = bsContainer.length > 0 ? bsContainer : node.element;
            //1.add or edit
            var dexist = false;
            if (node.data && String(node.data).length > 0 && (!(node.ExceptionsCount && node.ExceptionsCount>0))) dexist = true;
            var cBtn = obj.showButton(obj.options.buttons.template, dexist ? obj.options.buttons.change : obj.options.buttons.add, bsContainer, obj, node);
            var dBtn = obj.showButton(obj.options.buttons.template, dexist ? obj.options.buttons.del : null, bsContainer, obj, node);
            var eBtn = obj.showButton(obj.options.buttons.template, dexist ? obj.options.buttons.edit : null, bsContainer, obj, node);
            var nodetitle = node.element.find("." + node.respreviewcss);
            nodetitle.click(function () { cBtn.button.click(obj, node, cBtn.button); });
            if (node.ExceptionsCount && node.ExceptionsCount > 0) {
                nodetitle.html("can't find element :[" + node.data + "]");
                nodetitle.addClass("error");
                node.data = "";
                obj.RefreshTextBox(node);
            }
            return node.element;
        };
    result.showButton= function (template, btn, container, obj, node) {
        var obj = this;
        var res = { button: btn, element: null };
        if (btn) {            
            var resHtml = obj.TransformTemplate(btn.template ? btn.template : template, btn);
            var el = jQuery(resHtml.result);
            el.appendTo(container);
            res.element = el;
            el.click(function () { btn.click(obj, node, res) });
        }
        return res;
    };
    result.getNodeInfo = function (service, node, delegate) {
        var obj = this;
        node.uuidFast = obj.options.uuidFast();
        var resurl = obj.TransformTemplate(service.url, node);
        jQuery.getJSON(resurl.result, {}, function (d, txtstatus) {
            node = jQuery.extend({}, node, d); //extend existing data
            if (node.CContentTypeIcon) {
                node.icon = obj.options.content.iconspath + (String(node.CContentTypeIcon).charAt(0) != '.' ? node.CContentTypeIcon : obj.options.content.defaultIcon);
            }
            node.title = node.TreePath ? node.TreePath : node.title;
            node.title = node.title.length > 55 ? "<span class='bigtext'>" + String(node.title).substr(0, 50) + "...</span>" : node.title;
            if (node.CContentType && node.CContentType.alias) node.alias = node.CContentType.Alias;
            delegate(node, obj);
        });
    };
    result.show = function (node) {
        var obj = this;        
        obj.options.node = node ? node : obj.options.node;
        var resHtml = obj.TransformTemplate(obj.options.container.template, obj);
        obj.container = jQuery(resHtml.result);
        obj.container.appendTo(obj.txtEl.parent()); //generate main container
        obj.RenderNode();
    };
    result.RenderNode = function () {
        var obj = this;
        var cnode = obj.options.node;


        //clear all existing nodes
        obj.container.nodes = obj.container.nodes ? obj.container.nodes : [];
        jQuery(obj.container.nodes).each(function (pos, el) {
            el.element.remove();
        });
        //add current node inofrmation
        cnode.title = cnode.data && String(cnode.data).length > 0 ? cnode.data : cnode.title;
        cnode.pickername = obj.options.prevalue && obj.options.prevalue.name ? obj.options.prevalue.name : "content";
        cnode.picker = obj.options[cnode.pickername];
        cnode.startfrom = obj.options.prevalue.start ? obj.options.prevalue.start : ""; //rewrite start from
        cnode.service = cnode.picker.service ? cnode.picker : obj.options.service; //rewrite more node infor service
        cnode.template = cnode.picker.template ? cnode.picker.template : cnode.template; //rewrite node template
        cnode.ExceptionsCount = 0;//clear current exceptions-service will return new value
        obj.showNodeInfo(cnode.service, cnode, obj.container); //show node general information

        obj.getNodeInfo(cnode.service, cnode, function (n, o) {//extend general information with data from service (data doesn't exist any more, or with icon or with selection info)
            obj.options.node = cnode = n ? n : cnode;
            obj.RefreshTextBox(cnode);
            obj.showNodeInfo(cnode.service, cnode, obj.container); //refresh node with data which comes from the service
        });


    }

    return result;
}

ISM_SimpleItemPicker.prototype.options =
{
    service: {
        url: "/umbraco/webservices/TreeNodeData.ashx?id=##data##&rnd=##uuidFast##&treeType=##pickername##"
    },
    content: {
        title: 'Choose an content node',
        url: '/umbraco/dialogs/treepickerex.aspx?rnd=##uuidFast##=-1&treeType=content&contextMenu=true&isDialog=false&app=content&nodeKey=##startfrom##&selected=##Path##',
        iconspath: '/umbraco/images/umbraco/',
        defaultIcon: 'folder.gif',
        editurl: '/umbraco/editContent.aspx?id=##data##',
        cursiteid: -1,
        cursettingsid: -1,
        curhomeid: -1,
        sitedefaultpageid: -1,
        curpageid: -1,
        width: 400, height: 600
    },
    media: {
        title: 'Choose an media node',
        url: '/umbraco/dialogs/mediaPickerEx.aspx?rndo=##uuidFast##&treeType=media&contextMenu=true&isDialog=false&app=media&selected=##Path##',
        iconspath: '/umbraco/images/umbraco/',
        defaultIcon: 'folder.gif',
        editurl: '/umbraco/editMedia.aspx?id=##data##',
        cursiteid: -1,
        cursettingsid: -1,
        curhomeid: -1,
        sitedefaultpageid: -1,
        curpageid: -1,
        width: 540, height: 600
    },
    member: {
        title: 'Choose an member',
        url: '/umbraco/dialogs/treepickerex.aspx?rndo=##uuidFast##&treeType=member&contextMenu=true&isDialog=false&app=member&selected=##Path##',
        iconspath: '/umbraco/images/umbraco/',
        defaultIcon: 'folder.gif',
        editurl: '/umbraco/editMedia.aspx?id=##data##',        
        cursiteid: -1,
        cursettingsid: -1,
        curhomeid: -1,
        sitedefaultpageid: -1,
        curpageid: -1,
        width: 540, height: 600
    },
    fsobjects: {
        title: 'Choose an File',
        url: '/umbraco/dialogs/treepickerex.aspx?rnd=##uuidFast##=-1&treeType=fsobjects&contextMenu=false&isDialog=true&app=fsobjects&nodeKey=##startfrom##&selected=##Path##',
        iconspath: '/umbraco/images/umbraco/',
        defaultIcon: 'folder.gif',
        editurl: '',        
        cursiteid: -1,
        cursettingsid: -1,
        curhomeid: -1,
        sitedefaultpageid: -1,
        curpageid: -1,
        width: 540, height: 600,
        template: "<li class='nodedata' title='##data##'><span class='resdata'></span><span class='##respreviewcss##' title='##data##   (click to modify)'><img src='##icon##' alt='##data##' class='icon'/><span class='title'>##title##</span></span><span class='##buttonscss##'></span></li>",
        blockService:true
    },
    node: {},
    defaultnode: {//default node information
        template: "<li class='nodedata' title='##data##'><span class='resdata'></span><span class='##respreviewcss##' title='[##data##]   (click to modify)'><img src='##icon##' alt='##data##' class='icon'/><span class='title'>##title##</span></span><span class='##buttonscss##'></span></li>",
        icon: "/umbraco/images/umbraco/transparent.png",
        data: "",
        title: "[empty]",
        buttonscss: "buttons",
        respreviewcss: "respreview",
        startfrom: -1,
        picker:"content"
    },
    container: {
        template: "<ul class='contentitempicker'></ul>"
    },
    buttons: {
        template: "<span class='button button_##name## ##css##' title='##name##'><image src='##icon##' alt='##name##'/><span>",
        change: {
            icon: "/umbraco/images/fieldtypes/change16.png", //change16.png
            name: "change",
            css: "change_btn",
            click: function (obj, node, btn, url) {
                var resUrl = url = url ? url : obj.TransformTemplate(node.picker.url, node);
                obj.options.buttons.add.click(obj, node, btn, resUrl);
            }
        },
        del: {
            icon: "/umbraco/images/fieldtypes/del16.png",
            name: "clear",
            css: "del_btn",
            click: function (obj, node, btn) {
                obj.options.node = jQuery.extend(true, {}, obj.options.defaultnode);
                obj.RenderNode();
            }
        },
        add: {
            icon: "/umbraco/images/fieldtypes/add16.png",
            name: "add",
            css: "add_btn",
            click: function (obj, node, btn, url) {                
                var resUrl = url = url ? url : obj.TransformTemplate(node.picker.url, node);
                var delegate = function (modalWnd) {
                    var resval = modalWnd && modalWnd.outVal ? String(modalWnd.outVal) : "";
                    if (resval.length > 0) {
                        obj.options.node.data = resval;
                    };                    
                    obj.RenderNode();
                };
                UmbClientMgr.openModalWindow(resUrl.result, node.picker.title, true, node.picker.width, node.picker.height, 0, 0, false, delegate);
                return false;
            }
        },
        edit: {
            icon: "/umbraco/images/fieldtypes/edit16.png",
            name: 'open',
            css: 'open_btn',
            click: function (obj, node, btn, url) {
                var resUrl = url ? url : obj.TransformTemplate(node.picker.editurl, node);
                UmbClientMgr.openModalWindow(resUrl.result, "edit selected node data", true, 750, 600, 0, 0, false, function () { obj.RenderNode(); });
            }
        }
    },
    uuidFast: function () {
        var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'.split(''), uuid = new Array(36), rnd = 0, r;
        for (var i = 0; i < 36; i++) {
            if (i == 8 || i == 13 || i == 18 || i == 23) {
                uuid[i] = '-';
            } else if (i == 14) {
                uuid[i] = '4';
            } else {
                if (rnd <= 0x02) rnd = 0x2000000 + (Math.random() * 0x1000000) | 0;
                r = rnd & 0xf;
                rnd = rnd >> 4;
                uuid[i] = chars[(i == 19) ? (r & 0x3) | 0x8 : r];
            }
        }
        var s = uuid.join('').replace(/-/g, "");

        return s;
    }
};
























/*-------   single item picker(below): prevalue editor ---------*/


function ISM_SimpleItemPickerPreValue(txtElId, options) {
    var $this = jQuery(this);
    var result = {
        txtElId: txtElId,
        txtEl: jQuery("#" + txtElId),
        DataFromText: function () {
            var obj = this;
            var s = obj.txtEl.val();
            if (s && s.length > 0) {
                var result = { current: 'content', pickers: [{ name: 'content', value: { name: 'exact', text: 1036}}] };
                try {
                    eval("result=" + s + ";"); //get result from text box as json object
                } catch (err) {
                    //
                }
                obj.picker = result.current;
                jQuery(result.pickers).each(function (pos, picker) {
                    jQuery(obj.pickers).each(function (pos, rpicker) {
                        if (picker.name == rpicker.name) {
                            rpicker.value = jQuery.extend(true, rpicker.value, picker.value);
                            return false; //break current looping if we have found result
                        }
                    });
                });

            }
            return obj;
        },
        DataToText: function () {
            var obj = this;
            var res = "{current:'" + obj.picker + "',";
            res = res + "pickers:[";

            jQuery(obj.pickers).each(function (pos, picker) {
                var txt = picker.value.text ? picker.value.text : '';
                txt = String(txt).replace(/\\/g, "/");
                var val = picker.value.name ? picker.value.name : '';
                if (picker.value) res = res + "{name:'" + picker.name + "',value:{name:'" + val + "',text:'" + txt + "'} },";
                else res = res + "{name:'" + picker.name + "',value:{} },";
            });

            res = res + "{}]}";
            obj.txtEl.val(res);
        },
        templates: {
            main: "<div class='singlepicker singlepicker_##name##'><input type='checkbox' name='choosesinglepicker_##mainid##' value='##name##'/><span class='title pickertitle'>##name##</span></div>", //radio button to show "choose this picker"
            item: "<div class='item'><span><input type='radio' name='##mainid##_val' value='##value##'/></span><span>##title##</span></div>",
            txtbox: "<span class='txteditor'><input type='text' value='##text##'/></span>"
        },
        showPickerExtra: function (picker, obj) {
            obj = obj ? obj : result;
            var pttl = picker.title.find("input");
            var checked = pttl && pttl.length > 0 && pttl.attr('checked') != '';
            if (checked) {
                obj.picker = picker.name;
                obj.DataToText(); //refresh text box data
                jQuery(obj.pickers).each(function (pos, el) {
                    if (el.values && el.values.container) {
                        if (picker.name == el.name)
                            el.values.container.show();
                        else {
                            el.values.container.hide();
                        }
                    };
                    if (el.title && picker.name != el.name) {//uncheck others
                        var pttl = el.title.find("input");
                        if (pttl && pttl.length > 0 && pttl.attr('checked') != '') pttl.removeAttr('checked');
                    }
                });
            }
        },
        showPicker: function (cur, obj) {
            obj = obj ? obj : result;
            //show title part
            cur.title = jQuery(obj.TransformTemplate(obj.templates.main, cur, obj).result);
            cur.title.appendTo(cur.body);

            var tinput = cur.title.find("input");
            tinput.change(function () { obj.showPickerExtra(cur, obj); });
            if (tinput && cur.disabled) tinput.attr('disabled', 'disabled');
            //show extra values part
            if (cur.values && cur.values.length > 0) {
                cur.values.container = jQuery("<div class='prevalues' style='display:none;'></div>");
                cur.values.container.appendTo(cur.body);
                //show extra extra value
                jQuery(cur.values).each(function (pos, el) {
                    el.mainid = cur.mainid;
                    var hres = jQuery(obj.TransformTemplate(obj.templates.item, el, obj).result);
                    hres.appendTo(cur.values.container);
                    //show textbox if it needed
                    var txtres = null;
                    if (el.txtbox == "1") {
                        if (cur.value.name == el.name) el.text = cur.value.text;
                        else el.text = el.text ? el.text : el.name;
                        txtres = jQuery(obj.TransformTemplate(obj.templates.txtbox, el, obj).result);
                        txtres.appendTo(hres);
                        txtres.bind("focusout", function () {
                            el.text = txtres.find("input").val();
                            obj.DataToText();
                        });
                    };
                    var vinput = hres.find("input");
                    vinput.change(function () {
                        cur.value = { 'name': el.name, 'text': txtres ? txtres.find("input").val() : el.text };

                        obj.DataToText();
                    });
                    if (cur.value.name == el.name) vinput.attr('checked', 'checked'); //init value
                });
            };
            //init value
            if (obj.picker == cur.name) {
                tinput.attr('checked', 'checked');
                obj.showPickerExtra(cur, obj);
            }

        },
        picker: "content",
        pickers: [
            { name: 'dtype',
                show: function (cur, obj) {
                    obj = obj ? obj : result;
                    var el = jQuery("<select></select>");
                    el.appendTo(cur.body);
                    el.change(function () {
                        cur.value = jQuery(this).val();
                        obj.DataToText();
                    });
                    jQuery(cur.values).each(function (pos, dt) {
                        var issel = cur.value == String(dt) ? " selected " : " ";
                        jQuery("<option value='" + dt + "' " + issel + ">" + dt + "</option>").appendTo(el);
                    });
                    cur.value = { value: el.val() }; //save current value, if it empty:or just to be sure that it is exist
                },
                value: 'integer',
                values: ['integer', 'ntext', 'nvarchar', '--date--']
            },
            { name: 'content', lable: 'Is [Content Type Picker]', disabled: false,

                value: -1,
                values: [
                                { name: 'exact', title: 'Top Level node:-1[Default Content] or 1066:[an exact node id]', txtbox: 1, text: '-1' },
                                { name: 'currt', title: 'From [Current page]', txtbox: 0 },
                                { name: 'levln', title: 'From [Top page] with an level or [Current page]', txtbox: 1, text: '1' },
                                { name: 'parnt', title: 'From [Parent page] with an level or [Current page]', txtbox: 1, text: '1' },
                                { name: 'stype', title: 'From high levels page with specific type:(settings,homepage,etc)', txtbox: 1, text: 'settings' },
                                { name: 'tprop', title: 'From node, which [id] locates in First Level node, in the property with name: (defaultpage, contact,specific data -needs to be an integer field)', txtbox: 1, text: 'defaultpage' }
                        ]
            },
            { name: 'media', lable: 'Is [Media Picker]', disabled: false,
                value: -1,
                values: []
            },
            { name: 'member', lable: 'Is [Member Picker]', disabled: false,
                value: -1,
                values: []
            },
            { name: 'fsobjects', lable: 'Is [Folder Picker]', disabled: false,
                value: -1,
                values: [
                { name: 'js', title: 'JavaScript files', txtbox: 0, text: 'scripts' },
                { name: 'cs', title: 'Css StyleSheet files', txtbox: 0, text: 'css' },
                { name: 'ms', title: 'images\Media files', txtbox: 0, text: 'media/images' },
                { name: 'os', title: 'Other files', txtbox: 1, text: 'media/images' }
                ]
            }
        ],

        show: function () {//needs to show prevalue editor and all possible pickers and their settings
            var obj = this;
            obj.container = obj.txtEl.parent();
            var str = "<div class='prevalueeditor_singlepicker'></div>";
            obj.content = jQuery(str); obj.content.dtypes = {};
            obj.content.appendTo(obj.container);
            initcontent = function (el, pos) {
                el.main = obj; //add reference to main object
                el.mainid = obj.txtElId;
                el.container = jQuery("<div class='propertyItem " + el.selector + "'><div class='propertyItemheader'></div><div class='propertyItemContent'></div><br style='clear: both'/></div>");
                el.container.appendTo(obj.content);
                el.label = obj.options.labels[pos];

                el.header = el.container.find(".propertyItemheader"); el.header.html(el.label); //add lable to
                el.body = el.container.find(".propertyItemContent");
                return el;
            };
            jQuery(obj.pickers).each(function (pos, el) {
                initcontent(el, pos);
                if (typeof el.init == "function") el.init.call(obj, el, obj);
                if (typeof el.show == "function")
                    el.show.call(obj, el, obj); //show self method or
                else obj.showPicker.call(obj, el, obj); //show standard picker
            });
            obj.DataToText(); //refreshtext
        },
        TransformTemplate: function (template, element, obj) {
            obj = obj ? obj : result;
            var res = String(template);
            for (var pname in element) {
                res = res.replace(new RegExp("##" + pname + "##", "g"), element[pname]);
            }
            res = res.replace(new RegExp("##[^##]*##", "g"), ""); //replace rest to empty string
            return { 'result': res, 'template': template, 'data': element };
        }

    };

    
    result.options = jQuery.extend(true, {},result.DataFromText(), options);
    
    return result;

}